<template>
  <com-page class="page">
    <u-navbar placeholder
              autoBack
              :title="$t('pages_user_order_create_msg_e70764bf')" />
    <u-sticky>
      <ConcactCard :info="order.receiveInfo" @select-address="selectAddress" />
    </u-sticky>

    <view class="com-section card">
      <view class="com-p-y-md com-flex com-text-md">
        <u-icon name="home"
                class="com-pr-xs" />
        <text class="">官方旗舰店</text>
      </view>

      <view class="com-cell"
            v-for="item in order.goodsList"
            :key="item">
        <u-avatar :src="item.image"
                  size="85"
                  shape="square"
                  class="com-mr-sm" />
        <view class="com-cell__bd">
          <view class="com-text-md">{{ item.title }}</view>
          <view class="com-tag bg-gray com-m-y-xs">商品规格</view>
          <view class="com-tag sm bg-danger light com-m-y-xs">七天无理由退换</view>
        </view>
        <view class="com-cell__ft">
          <view class="com-text-price">{{ item.price | numberFormat }}</view>
          <view class="com-text-x">{{ item.number }}</view>
        </view>
      </view>

      <view class="">
        <view class="com-cell">
          <view class="com-cell__hd com-text-right com-mr-sm">配送方式</view>
          <view class="com-cell__bd">普通配送</view>

          <view class="com-cell__ft com-arrow">快递 免邮</view>
        </view>
        <view class="com-cell">
          <view class="com-cell__hd com-text-right com-mr-sm">配送时间</view>
          <view class="com-cell__bd">三天内送达</view>
        </view>
        <view class="com-cell">
          <view class="com-cell__hd com-text-right com-mr-sm">运费险</view>
          <view class="com-cell__bd">卖家赠送，退换货可赔</view>
        </view>
        <view class="com-cell">
          <view class="com-cell__hd com-text-right com-mr-sm">开具发票</view>
          <view class="com-cell__ft com-arrow">本次不开具发票</view>
        </view>
        <view class="com-cell">
          <view class="com-cell__hd com-text-right com-mr-sm">订单备注</view>
          <view class="com-cell__bd">
            <u-input placeholder="选填，请先和商家协商一致"
                     border="none"
                     v-model="order.note" />
          </view>
        </view>
      </view>

      <view class="com-text-right com-spacing">
        <text class="com-text-sm com-mr-xs">共{{ order.totalQuantity }}件 </text>
        <text>小计：</text>
        <text class="com-text-price com-color-primary com-text-md">{{ order.totalPrice | numberFormat }}</text>
      </view>
    </view>

    <view class="com-submit-bar">
      <view class="com-submit-bar__text com-justify-end">
        合计：
        <text class="com-text-price com-text-lg com-color-primary">{{ order.totalPrice | numberFormat }}</text>
      </view>
      <view class="com-submit-bar__button com-color-primary-bg"
            :class="{ 'submitting': submitting }"
            @click="onSubmit">
        {{ submitting ? '提交中...' : '立即购买' }}
      </view>
    </view>
  </com-page>
</template>

<script>
import ConcactCard from './components/concact-card.vue'
import orderApi from '@/api/modules/order'
import { getDefaultAddress } from '@/api/modules/user'
export default {
  name: 'Order-Create',
  components: { ConcactCard },
  data() {
    return {
      order: {
        goodsList: [{ image: '' }],
        note: '',
        receiveInfo: null,
        totalQuantity: 0,
        totalPrice: 0
      },
      submitting: false
    }
  },
  async onLoad(options) {
    if (options.params) {
      this.order = JSON.parse(decodeURIComponent(options.params))
      console.log('订单数据:', this.order)
    }
    
    // 监听地址选择事件
    uni.$on('selectAddress', (address) => {
      console.log('选择的地址:', address)
      this.$set(this.order, 'receiveInfo', address)
    })
    
    // 如果没有地址信息，尝试加载默认地址
    if (!this.order.receiveInfo) {
      await this.loadDefaultAddress()
    }
  },
  
  onUnload() {
    // 移除事件监听
    uni.$off('selectAddress')
  },
  methods: {
    inputNote(event) {
      this.order.note = event.detail.value
    },
    async onSubmit() {
      // 检查收货地址
      if (!this.order.receiveInfo || !this.order.receiveInfo.id) {
        uni.showModal({
          title: this.$t('pages_category_category_text_02d9819d'),
          content: this.$t('pages_user_address_edit_desc_4a046009'),
          showCancel: false,
          success: () => {
            this.selectAddress()
          }
        })
        return
      }

      // 检查商品列表
      if (!this.order.goodsList || this.order.goodsList.length === 0) {
        this.$utils.toast(this.$t('pages_user_order_create_msg_b939e607'))
        return
      }

      try {
        this.submitting = true
        
        // 构造skuList参数，与category页面格式一致
        const skuList = this.order.goodsList.map(item => {
          // 构造 skuSpec 字符串
          let skuSpec = this.$t('pages_category_category_msg_064eb9e8')
          if (item.specs && Object.keys(item.specs).length > 0) {
            skuSpec = Object.entries(item.specs)
              .map(([key, value]) => `${key}: ${value}`)
              .join(', ')
          }

          return {
            productId: item.id,
            skuId: item.sku ? item.sku.id : null,
            productName: item.title,
            price: item.price,
            skuSpec: skuSpec,
            quantity: item.number || 1,
            outSkuId: item.outSkuId || null,
            outProductId: item.outProductId || item.id.toString(),
            brandName: item.brandName || '',
            categoryName: item.categoryName || '',
            pic: item.image || null
          }
        })

        const orderData = {
          addressId: this.order.receiveInfo.id,
          note: this.order.note || '',
          skuList: skuList
        }

        console.log('提交订单数据:', orderData)
        
        const res = await orderApi.create(orderData)
        console.log('创建订单结果:', res)
        
        uni.showModal({
          title: this.$t('pages_user_order_create_msg_f4cb7f0f'),
          content: '订单已提交，请等待处理',
          showCancel: false,
          success: () => {
            // 跳转到订单列表或订单详情
            uni.navigateBack({
              delta: 2 // 返回到商品详情页的上一页
            })
          }
        })
      } catch (error) {
        console.error('创建订单失败:', error)
        this.$utils.toast('订单创建失败，请重试')
      } finally {
        this.submitting = false
      }
    },

    // 加载默认地址
    async loadDefaultAddress() {
      try {
        const defaultAddress = await getDefaultAddress()
        if (defaultAddress && defaultAddress.id) {
          console.log('加载默认地址:', defaultAddress)
          this.$set(this.order, 'receiveInfo', defaultAddress)
        }
      } catch (error) {
        console.log('获取默认地址失败或无默认地址:', error)
        // 无默认地址是正常情况，不显示错误提示
      }
    },

    // 选择收货地址
    selectAddress() {
      uni.navigateTo({
        url: '/pages/user/address/address?mode=select'
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.page {
  padding-bottom: 100rpx;
}

.com-section.card .com-cell::after {
  border-width: 0;
}

.com-submit-bar {
  display: flex;
  position: fixed !important;
  z-index: 10;
  right: 0;
  bottom: 0;
  left: 0;
  height: 50px;
  border-top: 1px solid #ebedf0;
  background-color: #fff;

  .com-submit-bar__text {
    display: flex;
    flex: 1;
    align-items: center;
    padding: 10px 15px;
    color: var(--com-color-main);
    font-weight: 500;
  }

  .com-submit-bar__button {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 12rpx $com-spacing-row-base 12rpx 0;

    /* width: 110px; */
    padding: 0 40rpx;

    /* border-radius: 2px; */
    border-radius: 2500px;
    background-color: var(--com-color-primary);
    color: #fff;
    font-weight: 600;
  }
}
</style>
